/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sw2asteriskjava;

import AsteriskBean.BCdr;
import AsteriskDao.AsteriskManager;
import conn.bean.BCampana;
import conn.bean.BLinea;
import conn.dao.DLinea;
import conn.dao.DLlamada;
import it.sauronsoftware.cron4j.Scheduler;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.asteriskjava.manager.ManagerConnection;
import org.asteriskjava.manager.action.OriginateAction;
import org.asteriskjava.manager.response.ManagerResponse;

/**
 *
 * @author root
 */

/* Esta clase hereda de Scheduler. Su unica funcion es enviar la llamada
 */
public class ChasquiScheduler extends Scheduler {

    private static int timeout = 30000;
    private HiloWorker hiloWorker;
    private BCampana campanaAsociada;
    private boolean acaboCampana = false;
    int llamadasXHacer;

    public ChasquiScheduler(String programacion) {

        this.schedule(programacion, new Runnable() {

            public void run() {

                /*SE INSTANCIA EL HILO WORKER*/
                setHiloWorker(new HiloWorker());
              

                /*ESTO ES IMPORTANTE!:
                ACA SE LE DICE AL HILO WORKER QUE SEA LISTENER DE LOS EVENTOS
                DEL ASTERISK*/
                ManagerConnection managerConnection = AsteriskManagerConnection.getManagerConnection();
                managerConnection.addEventListener(hiloWorker);

                /*EL HILO WORKER INICIA, ESTARE EN BUCLE HASTA QUE SE TERMINEN TODAS LAS LLAMADAS */
                getHiloWorker().start();


                /*SE OBTIENEN LOS NUMEROS A LLAMAR*/
                DLinea dLinea = new DLinea();
                List<BLinea> listaLineas = (List<BLinea>) dLinea.getLineasxCampana(campanaAsociada.getIdCampana());

                /*UN FOR QUE LANCE LAS LLAMADAS*/
                for (int i = 0; i < listaLineas.size(); i++) {
                    System.out.println("LLAMANDO A LA LINEA: " + listaLineas.get(i).getNumero());
                    /*HAY QUE HACER LA LLAMADA A LA LINEA: FALTA CAMBIAR ESE GENERATE CALL*/
                    //if (campanaAsociada.getMensaje().getIdMensaje() == 1) {
                    generateCallwRecordedSound(managerConnection, "LOCAL/" + listaLineas.get(i).getNumero(), "from-internal", "custom/angela-service", "" + listaLineas.get(i).getNumero());
                    //} else if (campanaAsociada.getMensaje().getIdMensaje() == 2) {
                    //    generateCallwRecordedSound(managerConnection, "LOCAL/" + listaLineas.get(i).getNumero(), "from-internal", "custom/cobranza-coactiva", "" + listaLineas.get(i).getNumero());
                    //}else if (campanaAsociada.getMensaje().getIdMensaje() == 3) {
                    //   generateCallwRecordedSound(managerConnection, "LOCAL/" + listaLineas.get(i).getNumero(), "from-internal", "custom/voz-renzo", "" + listaLineas.get(i).getNumero());
                    //}


                }

                /*CUANDO SE ACABAN LAS LLAMADAS (SE SALE DEL FOR ANTERIOR)
                HACER QUE EL HILO WORKER TERMINE*/
                hiloWorker.setFaltanLlamadas(false);
                /*JOIN SIRVE PARA ESPERAR QUE EL HILO WORKER TERMINE*/
                try {
                    hiloWorker.join();
                } catch (InterruptedException ex) {
                    Logger.getLogger(ChasquiScheduler.class.getName()).log(Level.SEVERE, null, ex);
                }
                /*SE ACABO CON ESTA CAMPANA*/
                acaboCampana = true;
            }
        });

    }

    public void generateCallwRecordedSound(ManagerConnection managerConnection, String channel, String context, String sound, String extension) {
        try {
            OriginateAction originateAction;
            ManagerResponse originateResponse;
            originateAction = new OriginateAction();
            originateAction.setChannel(channel);
            originateAction.setContext(context);
            originateAction.setApplication("Playback");
            originateAction.setData(sound);
            originateAction.setCallerId("asterisk-java");
            originateAction.setExten(extension);
            originateAction.setPriority(new Integer(1));
            originateAction.setTimeout(new Integer(30000));
            originateAction.setAccount(String.valueOf(campanaAsociada.getIdCampana()));

            managerConnection.login();
            originateResponse = managerConnection.sendAction(originateAction, timeout);
            System.out.println(originateResponse.getResponse());

            //  if(originateResponse.getResponse()==)
            /*DORMIR 10 SEGUNDOS HASTA Q LOS EVENTOS LLEGUEN AL HILO WORKER */
            Thread.sleep(10000);
            managerConnection.logoff();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public HiloWorker getHiloWorker() {
        return hiloWorker;
    }

    public void setHiloWorker(HiloWorker hiloWorker) {
        this.hiloWorker = hiloWorker;
    }

    public BCampana getCampanaAsociada() {
        return campanaAsociada;
    }

    public void setCampanaAsociada(BCampana campanaAsociada) {
        this.campanaAsociada = campanaAsociada;
    }

    public boolean isAcaboCampana() {
        return acaboCampana;
    }

    public void setAcaboCampana(boolean acaboCampana) {
        this.acaboCampana = acaboCampana;
    }
}
